<?php
/**
 * Created by PhpStorm.
 * User: chengchaogui
 * Date: 2017/9/24
 * Time: 20:27
 */

namespace App\Repository\Service;


use App\Framework\Config\SystemConstant;

trait BaseApiService
{
    /**
     * 校验签名
     * @param $params
     * @return array
     */
    protected function checkSign($params)
    {
        $sign = array_key_exists('sign', $params) ? $params['sign'] : '';

        if (empty($sign)) {
            return Message::setFalse('缺少签名参数');
        }

        unset($params['sign']);

        if ($sign != $this->generateMd5Sign($params)) {
            return Message::setFalse('签名验证错误');
        }

        return Message::setTrue('验证通过');
    }


    /**
     * md5方式签名
     * @param $params
     * @return string
     */
    protected function generateMd5Sign($params)
    {
        unset($params['_url']);//laravel会自动追加_url参数，用于识别路径，所以在此需要将其移除
        ksort($params);

        $string = '';
        foreach ($params as $k => $v) {
            $string .= $k . '=' . $v . '&';
        }

        $signStr = rtrim($string, '&') . SystemConstant::API_SIGN_KEY;
        return strtolower(md5($signStr));
    }

    /**
     * 获取api查询字符串
     * @param $params
     * @return string
     */
    protected function getApiQueryString($params)
    {
        $string = '';
        foreach ($params as $k => $v) {
            $string .= $k . '=' . urlencode($v) . '&';
        }

        $queryStr = rtrim($string, '&');
        return $queryStr;
    }
}